from openai import OpenAI
import json

import jsonReader
import chatbot.messageList

class FunctionResponser:
    def __init__(self, defaultSetting, characterName, tools):
        # 初始化 FunctionResponser 对象。
        # defaultSetting: 初始设定
        # characterName: 默认的AI角色名
        # tools: AI可以调用的方法库
        # 读取 API 凭证
        api_credentials = jsonReader.JsonFileReader('./resource/api-key.json').read_json_file()
        if api_credentials:
            self.client = OpenAI(
                api_key=api_credentials['apiKey'],
                base_url=api_credentials['baseUrl']
            )
        else:
            raise ValueError("API credentials not found or invalid.")

        # 初始化 MessageContent 类
        self.messageList = chatbot.messageList.MessageContent(defaultSetting)
        # 初始化AI设置
        self.characterName = characterName
        self.model = "GLM-4-Plus"
        self.temprature = 0.9
        self.top_p = 0.7
        self.tools = tools

    def next(self, content):
        # 添加用户消息到消息列表并发送到AI
        self.messageList.addMessage('user', content)
        return self.getResponse()

    def speak(self):
        # 展示最后一条消息
        print(f'你的{self.characterName}说：{self.messageList.getLastMessage()}')


    def call_tool(self, tool_calls):
        # 解析tool_calls 并调用工具库获取返回值
        call = tool_calls[0]
        name = call.function.name
        args = json.loads(call.function.arguments)
        result = self.tools.call_tool(name, args)
        self.messageList.addToolReturn(call.id, result)
        return self.getResponse()


    def getResponse(self):
        # 获取流式响应
        response = self.client.chat.completions.create(
            model=self.model,
            messages=self.messageList.getMessageList(),
            top_p=self.top_p,
            temperature=self.temprature,
            tools=self.tools.toolDescription
        )
    
        if response.choices:
            choice = response.choices[0]
            message = choice.message
            if message.content and message.tool_calls == None:
                # 添加AI消息到消息列表
                self.messageList.addMessage('assistant', message.content)
                return self
            if message.tool_calls:
                return self.call_tool(message.tool_calls)

    def get_message_list(self):
        return self.messageList.getMessageList()